package com.llb.llbliving.commodity.exception;

import com.llb.common.exception.LlblivingCodeEnum;
import com.llb.common.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.HashMap;
import java.util.Map;


/*
* @ResponseBody表示以json格式返回数据
* @ControllerAdvice(basePackages = "com.llb.llbliving.commodity.controller")
* 统一接管com.llb.llbliving.commodity.controller包下抛出的异常
* */
@Slf4j
@ResponseBody
@ControllerAdvice(basePackages = "com.llb.llbliving.commodity.controller")
public class LlblivingExceptionControllerAdvice {
    /*
    * 表示如果com.llb.llbliving.commodity.controller包下的类抛出了MethodArgumentNotValidException异常
    * 就由这个方法来处理
    * */
    @ExceptionHandler({MethodArgumentNotValidException.class})
    public R handlerValidException(MethodArgumentNotValidException ex){
        System.out.println(ex.getMessage());
        //System.out.println(ex.getMessage());
        //得到BindingResult
        BindingResult bindingResult = ex.getBindingResult();
        Map<String, String> errorMap = new HashMap<>();
        //遍历bindingResult,将校验错误信息收集map
        bindingResult.getFieldErrors().forEach(fieldError -> {
            errorMap.put(fieldError.getField(),fieldError.getDefaultMessage());
        });
        return R.error(LlblivingCodeEnum.INVALID_EXCEPTION.getCode()
                ,LlblivingCodeEnum.INVALID_EXCEPTION.getMsg()).
                put("data",errorMap);
    }
    /*
    * 编写方法，处理没有精确匹配到的异常/错误
    * 返回一个统一的信息
    * Throwable是异常类的顶级类
    * */
    @ExceptionHandler(Throwable.class)
    public R handlerException(Throwable throwable){
        System.out.println(throwable.getMessage());
        return R.error(LlblivingCodeEnum.UNKNOWN_EXCEPTION.getCode()
                ,LlblivingCodeEnum.UNKNOWN_EXCEPTION.getMsg());
    }

}
